package com.android2024.no6_music;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.animation.ObjectAnimator;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.text.SimpleDateFormat;

public class MainActivity extends AppCompatActivity
        //控件点击事件 ， 进度条变化事件
        implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        initHandle();
        //初始化动画
        InitAnimator();
        //初始化进度条
        initSeekBar();
        //初始化音乐功能按键
        initMusicKey();
        //音乐数据
        initMusicData();
        //绑定服务
        Connect();
    }

    //acitivy 结束的时候调用的方法
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //接触绑定
        UnBind();
    }

    /** 检测权限后的回调 **/
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(!JwPermissions.isHavePermissions(this,MusicData.permArr)){
            //判断权限是否允许，运行时初始化音乐数据
            musicData.init();
        }else{
            //权限不允许 弹出对话框
            JwPermissions.showNormalDialog(this);
        }
    }

    /** 音乐数据 **/
    static MusicData musicData;
    private void initMusicData(){
        musicData = new MusicData(this){
            @Override
            public void setChooseMusic(Music chooseMusic) {
                super.setChooseMusic(chooseMusic);
                //更换歌曲时更换界面上歌曲名称 并播放歌曲
                TextView nameView = findViewById(R.id.name);
                nameView.setText(chooseMusic.name);
                play();
            }
        };
    }
    /** 动画 **/
    private ObjectAnimator mAnimator; // 动画类
    private ImageView dpView ;
    private void InitAnimator()
    {
        dpView = findViewById(R.id.dp);
        //绑定动画对象 对图片进行旋转动画的显示 rotation--动画名称 0f,360.0f 动画旋转角度 重0--360°
        mAnimator = ObjectAnimator.ofFloat(dpView,"rotation",0f,360.0f);
        //设置动画旋转一周事件 1000--1s  10000-10s
        mAnimator.setDuration(1000);
        //插值器（动画 匀速 加速 减速 等效果） 默认匀速
        mAnimator.setInterpolator(new LinearInterpolator());
        //设置无限循环
        mAnimator.setRepeatCount(-1);
        //mAnimator.start();
    }

    /** 进度条 **/
    private static SeekBar seekBar;
    private static TextView timeView,maxTimeView;
    private void initSeekBar(){
        seekBar = findViewById(R.id.seekbar);
        seekBar.setOnSeekBarChangeListener(this);
        timeView = findViewById(R.id.time);
        maxTimeView = findViewById(R.id.maxTime);
    }
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("mm:ss");
    static Handler handler;
    ProgressBar progressBar;
    private void initHandle(){
        progressBar = findViewById(R.id.progress);
        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                progressBar.setVisibility(View.GONE);
                if (msg.what == 0) {
                    MusicService.MusicTime musicTime = (MusicService.MusicTime) msg.obj;
                    if (musicTime.maxTime == musicTime.time) {
                        //播放完自动播放下一首
                        musicData.next();
                    } else {
                        seekBar.setMax(musicTime.maxTime);
                        seekBar.setProgress(musicTime.time);
                        timeView.setText(dateFormat.format(musicTime.time));
                        maxTimeView.setText(dateFormat.format(musicTime.maxTime));
                    }
                }
                else if(msg.what==1){
                    Toast.makeText(MainActivity.this,"服务器连接失败",Toast.LENGTH_LONG).show();
                }
                else if(msg.what==2){
                    progressBar.setVisibility(View.VISIBLE);
                }
            }
        };
    }
    /** 功能按键 **/
    View playView,stopView;
    private void initMusicKey(){
        playView = findViewById(R.id.play);
        stopView = findViewById(R.id.stop);
        playView.setOnClickListener(this);
        stopView.setOnClickListener(this);
        findViewById(R.id.list).setOnClickListener(this);
        findViewById(R.id.last).setOnClickListener(this);
        findViewById(R.id.next).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.play:
                play();
                break;
            case R.id.stop:
                stop();
                break;
            case R.id.last:
                last();
                break;
            case R.id.next:
                next();
                break;
            case R.id.list:
                list();
                break;

        }
    }

    //播放按钮
    void play(){
        if(mBinder!=null&&musicData.chooseMusic!=null)
        {
            mAnimator.start();
            playView.setVisibility(View.GONE);
            stopView.setVisibility(View.VISIBLE);
            mBinder.play(musicData.chooseMusic);
        }
    }
    //停止 暂停按钮
    void stop(){
        mAnimator.pause();
        stopView.setVisibility(View.GONE);
        playView.setVisibility(View.VISIBLE);
        mBinder.pause();
    }
    //上一首
    void last(){
        musicData.last();
    }
    //下一首
    void next(){
        musicData.next();
    }
    //进入音乐列表
    void list(){
        Intent intent = new Intent();
        intent.setClass(this,ListActivity.class);
        startActivity(intent);
    }
    //服务
    //服务对象
    private MusicService.MusicBinder mBinder;
    //服务连接
    private ServiceConnection mCnn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //连接成功 返回服务对象
            mBinder = (MusicService.MusicBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            //服务断开
        }
    };
    //绑定服务
    Intent intent;
    private void Connect()
    {
        intent = new Intent(this,MusicService.class);
        bindService(intent, mCnn,BIND_AUTO_CREATE);
    }
    //解除绑定
    public void UnBind()
    {
        if(mBinder!=null)
        {
            unbindService(mCnn);
            stopService(intent);
        }
    }

    //进度条变化的时候调用该方法
    @Override
    public void onProgressChanged(SeekBar seekBar, int i, boolean b) {

    }

    //进度条开始触发的时候调用该方法
    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    //进度条结束的时候调用该方法
    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if(mBinder!=null)
            mBinder.seekTo(seekBar.getProgress());
    }
}